package se.devoteam.nexus.ldap;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Set;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;

import org.apache.directory.server.core.configuration.MutablePartitionConfiguration;
import org.apache.directory.server.unit.AbstractServerTest;

/**
 * Create and set up an LDAP test server which is used for tests.
 */
public class LdapTestServer extends AbstractServerTest {

	/**
	 * Initialize the server.
	 */
	public void setUp() throws Exception {
		// Add partition 'sevenSeas'
		MutablePartitionConfiguration pcfg = new MutablePartitionConfiguration();
		pcfg.setName("dn");
		pcfg.setSuffix("dc=example,dc=devoteam,dc=se");

		// Create some indices
		Set<String> indexedAttrs = new HashSet<String>();
		indexedAttrs.add("objectClass");
		indexedAttrs.add("o");
		pcfg.setIndexedAttributes(indexedAttrs);

		// Create a first entry associated to the partition
		Attributes attrs = new BasicAttributes(true);

		// First, the objectClass attribute
		Attribute attr = new BasicAttribute("objectClass");
		attr.add("top");
		attr.add("organization");
		attrs.put(attr);

		// Associate this entry to the partition
		pcfg.setContextEntry(attrs);

		// As we can create more than one partition, we must store
		// each created partition in a Set before initialization
		Set<MutablePartitionConfiguration> pcfgs = new HashSet<MutablePartitionConfiguration>();
		pcfgs.add(pcfg);

		configuration.setContextPartitionConfigurations(pcfgs);

		// Create a working directory
		File workingDirectory = new File("target/apacheds-work");
		configuration.setWorkingDirectory(workingDirectory);

		super.setUp();

		// Load a demo ldif file
		String basedir = new File("").getAbsolutePath();
		FileInputStream fis = new FileInputStream(new File(basedir + "/target/test-classes/example.ldif"));
		if (null == fis) {
			throw new RuntimeException("The boostrap LDIF file has not been found.");
		}

		this.importLdif(fis);

		// Why does this result in a null InputStream?
		// importLdif( this.getClass().getResourceAsStream( getBasedir() +
		// "/target/test-classes/example.ldif" ));
	}

	/**
	 * Shut down the server.
	 */
	public void tearDown() throws Exception {
		super.tearDown();
	}
}
